package com.hui.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.hui.server.entity.*;
import com.hui.server.service.*;
import com.hui.server.util.RespPageBean;
import com.hui.server.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hui
 * @since 2022-03-31
 */
@Api(tags = "EmployeeController")
@RestController
@RequestMapping("/employee/basic/employee")
@Slf4j
public class EmployeeController {

    private final EmployeeService employeeService;
    private final JoblevelService joblevelService;
    private final PoliticsStatusService politicsStatusService;
    private final NationService nationService;
    private final PositionService positionService;
    private final DepartmentService departmentService;

    @Autowired
    public EmployeeController(EmployeeService employeeService, JoblevelService joblevelService,
                              PoliticsStatusService politicsStatusService, NationService nationService,
                              PositionService positionService, DepartmentService departmentService) {
        this.employeeService = employeeService;
        this.joblevelService = joblevelService;
        this.politicsStatusService = politicsStatusService;
        this.nationService = nationService;
        this.positionService = positionService;
        this.departmentService = departmentService;
    }

    /**
     * swagger 会报错： LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", defaultValue, type), e);建议以后换swagger版本<br/>
     * swagger 无法测试 localDate[] 数组，两个日期之间的查询，但是SQL与方法都是对的
     *
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    @ApiOperation(value = "获取所有员工（分页），并按照指定条件模糊查询")
    @GetMapping("/")
    public RespPageBean getEmployeeByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer size,
                                          Employee employee, LocalDate[] beginDateScope) {

        log.error(employee.toString());
        return employeeService.getEmployeeByPage(currentPage, size, employee, beginDateScope);
    }


    @ApiOperation("添加员工")
    @PostMapping("/")
    public Result<?> insertEmployee(@RequestBody Employee employee) {
        return employeeService.insertEmployee(employee);
    }


    @ApiOperation(value = "更新员工")
    @PutMapping("/")
    public Result<?> updateEmp(@RequestBody Employee employee) {
        if (employeeService.updateById(employee)) {
            return Result.success("更新成功");
        }
        return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "更新失败！");
    }

    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public Result<?> deleteEmp(@PathVariable Integer id) {
        if (employeeService.removeById(id)) {
            return Result.success("删除成功");
        }
        return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "删除失败！");
    }


    @ApiOperation(value = "获取插入员工所需要的工号，数据库中最大的工号加一，保证唯一性")
    @GetMapping("/maxWorkID")
    public Result<?> maxWorkID() {
        return employeeService.maxWorkId();
    }


    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response, @RequestParam(defaultValue = "-1", required = false) Integer id) {
        //查出数据
        List<Employee> list = employeeService.getAllEmployeeOrOneById(id);
        //HSSF对应97-2003版本的Excel，XSSF则对应2007版本的Excel。
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type", "application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls", StandardCharsets.UTF_8));
            outputStream = response.getOutputStream();
            //workbook.write(response.getOutputStream());
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "上传文件", dataType = "MultipartFile")})
    @PostMapping("/import")
    public Result<?> importEmployee(MultipartFile file) {
        ImportParams params = new ImportParams();
        //设置去掉标题行
        params.setTitleRows(1);

        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> statusList = politicsStatusService.list();
        List<Department> departmentList = departmentService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Position> positionList = positionService.list();
        try {
            List<Employee> employeeList = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            //用 foreach 会更好
            List<Employee> insertListData = employeeList.stream().map(data -> {
                //民族
                Integer nationId = nationList.get(nationList.indexOf(data.getNation())).getId();
                data.setNationId(nationId);
                //政治面貌
                Integer statusId = statusList.get(statusList.indexOf(data.getPoliticsStatus())).getId();
                data.setPoliticId(statusId);
                //部门
                Integer depId = departmentList.get(departmentList.indexOf(data.getDepartment())).getId();
                data.setDepartmentId(depId);
                //职称
                Integer jobLevelId = joblevelList.get(joblevelList.indexOf(data.getJoblevel())).getId();
                data.setJobLevelId(jobLevelId);

                Integer posId = positionList.get(positionList.indexOf(data.getPosition())).getId();
                data.setPosId(posId);

                return data;
            }).collect(Collectors.toList());

            boolean saveBatch = employeeService.saveBatch(insertListData);
            return saveBatch ?
                    Result.success("导入成功！") :
                    Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "导入失败！");
        } catch (Exception e) {
            log.error("导入失败，错误信息：{}", e.getMessage());
//            e.printStackTrace();
        }

        return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "导入失败！");
    }


    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsStatus")
    private Result<?> getAllPoliticsStatus() {
        return Result.success(politicsStatusService.list());
    }

    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevel")
    public Result<?> getAllJobLevel() {
        return Result.success(joblevelService.list());

    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public Result<?> getAllNation() {
        return Result.success(nationService.list());
    }

    @ApiOperation(value = "获取所有职位")
    @GetMapping("/position")
    public Result<?> getAllPosition() {
        return Result.success(positionService.list());

    }

    @ApiOperation(value = "获取所有部门")
    @GetMapping("/deps")
    public Result<?> getAllDepartment() {
        return departmentService.getAllDepartments();
    }


}

